﻿using System;
using System.Collections;
using System.Collections.Generic;
using NpcFramework;
using UnityEngine;
using UnityEngine.Rendering;

namespace Gameplay.PVE
{
    public class PveNpcPool : PvePrefabPool
    {
        private Dictionary<GameObject,LODGroup> _allLodGroups = new Dictionary<GameObject, LODGroup>();
        
        public PveNpcPool(PveResourceManager.EPveResType pveResType, int initNum, int capacity, string resPath, Transform root, Action<GameObject> completeAction = null) :
            base(pveResType, initNum, capacity, resPath, root, completeAction)
        {
            NFConstValue.onQualityChange += QualitySettings;
        }

        protected override GameObject ConstructItem()
        {
            GameObject o = base.ConstructItem();
            LODGroup lodGroup = o.GetComponent<LODGroup>();
            if (lodGroup)
            {
                _allLodGroups[o] = lodGroup;
                LODQuality(lodGroup);
            }
            return o;
        }
        

        public override void Destroy()
        {
            base.Destroy();
            _allLodGroups.Clear();
            NFConstValue.onQualityChange -= QualitySettings;
        }

        private void QualitySettings()
        {
            foreach (var lodGroup in _allLodGroups)
            {
                LODQuality(lodGroup.Value);
            }
        }

        private void LODQuality(LODGroup lodGroup)
        {
            if (lodGroup == null)
            {
                return;
            }

            var lods = lodGroup.GetLODs();
            for (int i = 0; i < lods.Length; i++)
            {
                foreach (var renderer in lods[i].renderers)
                {
                    if (i > NFConstValue.MAXShadowLOD)
                    {
                        renderer.shadowCastingMode = ShadowCastingMode.Off;
                        renderer.receiveShadows = false;
                    }
                    else
                    {
                        renderer.shadowCastingMode = ShadowCastingMode.On;
                        renderer.receiveShadows = true;
                    }
                }
            }
        }
    }
}
